package com.jay.base.lock;

/**
 * Created by caoyuan7 on 2019/4/26.
 */
public class Can {
    private Lock lock = new Lock();
    private int count = 0;
    public int inc() throws InterruptedException {
        lock.lock();
        this.count++;
        System.out.println(count);
        lock.unlock();
        return count;
    }

    public static void main(String args[]) throws InterruptedException {
        Can can = new Can();
        for(int i =0;i<100;i++){
            can.inc();
        }

    }


}
class Lock{
    boolean isLocked = false;
    Thread  lockedBy = null;
    int lockedCount = 0;
    public synchronized void lock()
            throws InterruptedException{
        Thread thread = Thread.currentThread();
        while(isLocked && lockedBy != thread){
            wait();
        }
        isLocked = true;
        lockedCount++;
        lockedBy = thread;
    }
    public synchronized void unlock(){
        if(Thread.currentThread() == this.lockedBy){
            lockedCount--;
            if(lockedCount == 0){
                isLocked = false;
                notify();
            }
        }
    }
}